<template>
  <view class="page">
    <!-- 用户信息区域 -->
    <view class="user-info">
      <view class="user-avatar">
        <image :src="userInfo.picture || 'https://via.placeholder.com/150'" class="avatar" />
      </view>
      <view class="user-details">
        <text class="user-name">{{ userInfo.name || '未登录' }}</text>
        <text class="user-id">护工编号: {{ userInfo.archiveCode || '请登录后查看' }}</text>
        <text class="user-level">等级: {{ userInfo.level }}</text>
        <text class="user-status">状态: {{ userInfo.serviceStatus }}</text>
      </view>
      <view v-if="!isLoggedIn" class="login-button" @click="handleLogin">
        <text>立即登录</text>
      </view>
    </view>

    <!-- 我的今日预约 -->
    <view class="today-appointments">
      <view class="section-header">
        <text class="section-title">我的今日预约</text>
        <text class="view-all" @click="showAllAppointments">全部</text>
      </view>
      <view v-if="displayAppointments.length > 0">
        <view class="appointment-item" v-for="(item, index) in displayAppointments" :key="index">
          <text class="service-name">{{ item.serviceName }}</text>
          <text class="time">{{ item.startTime }} - {{ item.endTime }}</text>
        </view>
      </view>
      
    </view>

    <view class="scan-btn-wrapper">
      <button class="scan-btn" @click="handleScan">
        <!-- <image src="../../../static/tabbar/scan.png" class="scan-icon" /> -->
        <text>扫一扫</text>
      </button>
    </view>
    <!-- 功能栏位 -->
    <view class="function-list">
      <view class="function-item" v-for="(item, index) in functionItems" :key="index" @click="navigateToPage(item.url)">
        <text>{{ item.title }}</text>
        <image class="arrow" src="../../../static/images/travel/personal/Clipped.png"></image>
      </view>
    </view>
  </view>

  <!-- Tabbar -->
  <view class="nurse-tabbar">
    <view 
      v-for="(item, index) in tabList" 
      :key="index" 
      class="tab-item"
      :class="{ active: currentIndex === index }"
      @click="handleTabClick(index)"
    >
      <image :src="currentIndex === index ? item.selectedIconPath : item.iconPath" class="tab-icon" />
      <text class="tab-text">{{ item.text }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getAllUserOrderList, updateUserOrderStatus } from '@/api/wxlogin/wxlogin'

import { useUserStore } from '@/store'
import { getCaregiverAssignmentList } from '@/api/nurse/caregiverassignment'

const userStore = useUserStore()
const isLoggedIn = ref(uni.getStorageSync('nurseisLoggedIn') || false)
const archiveId = ref(uni.getStorageSync('archiveId') || '')
const todayAppointments = ref([])
const allAppointments = ref([])
const showAll = ref(false)
const displayAppointments = ref([])
const noAppointmentText = ref('今日暂无预约')
const currentIndex = ref(2) // 默认选中个人中心

const tabList = ref([
  {
    iconPath: '../../../static/tabbar/home.png',
    selectedIconPath: '../../../static/tabbar/homeHL.png',
    text: '首页',
    pagePath: '/pages/nurse-platform/index/index'
  },
  {
    iconPath: '../../../static/tabbar/example.png',
    selectedIconPath: '../../../static/tabbar/exampleHL.png',
    text: '预约日历',
    pagePath: '/pages/nurse-platform/order/order'
  },
  {
    iconPath: '../../../static/tabbar/personalHL.png',
    selectedIconPath: '../../../static/tabbar/personalHL.png',
    text: '个人中心',
    pagePath: '/pages/nurse-platform/my/my'
  }
])

const handleTabClick = (index) => {
  if (currentIndex.value !== index) {
    currentIndex.value = index
    uni.reLaunch({ url: tabList.value[index].pagePath })
  }
}

const userInfo = ref({
  name: '',
  archiveCode: '',
  picture: '',
  level: '',
  serviceStatus: '',
  archiveId: ''
})

// 功能栏位列表
const functionItems = ref([
  { title: '安排事项', url: '/pages/nurse-platform/my/schedule' },
  { title: '我的所有预约', url: '/pages/nurse-platform/my/all-appointments' },
  { title: '修改个人资料', url: '/pages/nurse-platform/my/profile' },
  { title: '个人明细', url: '/pages/nurse-platform/my/details' },
  { title: '联系客服', url: '/pages/nurse-platform/my/customer-service' },
  { title: '公司介绍', url: '/pages/nurse-platform/my/company-intro' },
  { title: '开具发票', url: '/pages/nurse-platform/my/invoice' },
  { title: '退出登录', url: 'logout' }
])

const productOrders = ref([])


// 获取所有排班
const fetchAllAppointments = async () => {
  try {
    const res = await getCaregiverAssignmentList({ caregivergId: archiveId.value })
    if (res.code === 200) {
      const currentDate = new Date().toISOString().split('T')[0]
      allAppointments.value = res.data
        .filter(item => {
          const startDate = item.serviceStartDate
          const endDate = item.serviceEndDate
          return currentDate >= startDate && currentDate <= endDate
        })
        .map(item => ({
          serviceName: item.serviceName || '未命名服务',
          startTime: item.serviceStartTime,
          endTime: item.serviceEndTime,
          date: item.serviceStartDate
        }))
      displayAppointments.value = allAppointments.value
    }
  } catch (err) {
    console.error('获取排班列表失败:', err)
  }
}

// 显示所有待完成的服务项
const showAllAppointments = () => {
  uni.navigateTo({
    url: '/pages/nurse-platform/my/pending-services'
  })
}

const handleLogin = () => {
  uni.navigateTo({
    url: '/pages/login/index'
  })
}

const downloadFile = async (url) => {
  try {
    console.log('开始下载文件:', url);
    const res = await new Promise((resolve, reject) => {
      wx.downloadFile({
        url: url,
        success: function (res) {
          if (res.statusCode === 200) {
            console.log('文件下载成功，临时路径:', res.tempFilePath);
            resolve(res.tempFilePath);
          } else {
            console.error('文件下载失败，状态码:', res.statusCode);
            reject(new Error('下载文件失败'));
          }
        },
        fail: function (err) {
          console.error('文件下载失败:', err);
          reject(err);
        }
      });
    });
    return res;
  } catch (err) {
    console.error('文件下载失败:', err);
    return null;
  }
}

const navigateToPage = async (url) => {
  if (url === 'logout') {
    uni.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: function (res) {
        if (res.confirm) {
          // 清除登录状态和用户信息
          uni.removeStorageSync('nurseisLoggedIn')
          uni.removeStorageSync('nurseuserInfo')
          uni.removeStorageSync('archiveId')
          
          // 重置用户信息
          userInfo.value = {
            name: '',
            archiveCode: '',
            picture: '',
            level: '',
            serviceStatus: '',
            archiveId: ''
          }
          isLoggedIn.value = false
          
          // 显示提示
          uni.showToast({
            title: '已退出登录',
            icon: 'success',
            duration: 2000
          })
          
          // 延迟跳转到登录页面
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/entrance/index'
            })
          }, 2000)
        }
      }
    })
    return
  }

  if (url === '/pages/nurse-platform/my/company-intro') {
    console.log('开始下载文件...');
    uni.showLoading({
      title: '正在下载文件...',
      mask: true
    });
    try {
      const filePath = await downloadFile('https://cloud-minapp-47896.cloud.ifanrusercontent.com/1u7WveKJ7yV1KFlG.pdf');
      uni.hideLoading();
      if (filePath) {
        console.log('文件下载成功，路径:', filePath);
        wx.openDocument({
          filePath: filePath,
          fileType: 'pdf',
          success: function (res) {
            console.log('打开文档成功');
          },
          fail: function (err) {
            console.error('打开文档失败:', err);
            uni.showToast({
              title: '打开文档失败',
              icon: 'none'
            });
          }
        });
      } else {
        console.error('文件下载失败');
        uni.showToast({
          title: '文件下载失败',
          icon: 'none'
        });
      }
    } catch (err) {
      uni.hideLoading();
      console.error('文件下载失败:', err);
      uni.showToast({
        title: '文件下载失败',
        icon: 'none'
      });
    }
  } else {
    uni.navigateTo({ url })
  }
}

const handleFunctionClick = async (item) => {
  if (!isLoggedIn.value) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }

  if (item.text === '修改个人资料') {
    uni.showToast({
      title: '该功能待开发',
      icon: 'none'
    });
    return;
  }

  if (item.url === 'logout') {
    uni.showModal({
      title: '确认退出',
      content: '您确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除登录状态和用户信息
          uni.removeStorageSync('nurseisLoggedIn')
          uni.removeStorageSync('nurseuserInfo')
          isLoggedIn.value = false
          userInfo.value = {
            name: '',
            archiveCode: '',
            picture: '',
            level: '',
            serviceStatus: '',
            archiveId: ''
          }
          uni.showToast({
            title: '退出登录成功',
            icon: 'success'
          })
          // 返回登录页
          uni.navigateTo({
            url: '/pages/login/index'
          })
        }
      }
    })
  } else {
    uni.navigateTo({ url: item.url })
  }
};

// 扫码核销逻辑
const handleScan = () => {
  uni.scanCode({
    scanType: ['qrCode'],
    success: async (res) => {
      const orderNo = res.result // 二维码内容为 outTradeNo
      // 重新拉取订单，确保数据最新
      await fetchProductOrders()
      const order = productOrders.value.find(o => o.outTradeNo === orderNo)
      if (!order) {
        uni.showToast({ title: '未找到该订单', icon: 'none' })
        return
      }
      if (order.status !== 'PAID') {
        uni.showToast({ title: order.status === 'COMPLETED' ? '订单已核销' : '订单未支付', icon: 'none' })
        return
      }
      // 更新订单状态为已完成
      const updateRes = await updateUserOrderStatus({ id: order.id, status: 'COMPLETED' })
      if (updateRes.code === 200) {
        uni.showToast({ title: '核销成功', icon: 'success' })
        await fetchProductOrders()
      } else {
        uni.showToast({ title: '核销失败', icon: 'none' })
      }
    },
    fail: () => {
      uni.showToast({ title: '扫码失败', icon: 'none' })
    }
  })
}

// 获取全部商品订单
const fetchProductOrders = async () => {
  try {
    const res = await getAllUserOrderList()
    console.log("商品订单",res)
    if (res.code === 200) {
      productOrders.value = res.data || []
    }
  } catch (err) {
    uni.showToast({ title: '获取商品订单失败', icon: 'none' })
  }
}

// 页面加载和展示时都拉取一次
onMounted(() => {
  isLoggedIn.value = uni.getStorageSync('nurseisLoggedIn') || false
  if (isLoggedIn.value) {
    const storedUserInfo = uni.getStorageSync('nurseuserInfo')
    if (storedUserInfo) {
      userInfo.value = JSON.parse(storedUserInfo)
    }
    fetchAllAppointments()
  }
  fetchProductOrders() // 新增：页面加载时获取商品订单
})

onShow(() => {
  const nurseuserInfo = uni.getStorageSync('nurseuserInfo')
  if (nurseuserInfo) {
    userInfo.value = JSON.parse(nurseuserInfo)
  }
  isLoggedIn.value = uni.getStorageSync('nurseisLoggedIn') || false
  if (isLoggedIn.value) {
    fetchAllAppointments()
  }
  fetchProductOrders()
})
</script>

<style scoped lang="scss">
.page {
  padding: 20rpx;
}

.user-info {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.user-avatar {
  margin-right: 20rpx;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
}

.user-details {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.user-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.user-id,
.user-level,
.user-status {
  font-size: 28rpx;
  color: #666;
  margin-top: 6rpx;
}

.login-button {
  padding: 10rpx 20rpx;
  background-color: #ffcc00;
  border-radius: 8rpx;
  color: #333;
  font-size: 28rpx;
  cursor: pointer;
}

.today-appointments {
  margin-top: 30rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.view-all {
  font-size: 28rpx;
  color: #018d71;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  background-color: #f0f0f0;
}

.appointment-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.service-name {
  font-size: 28rpx;
  color: #333;
}

.time {
  font-size: 24rpx;
  color: #666;
  margin-top: 8rpx;
  display: block;
}

.no-appointment-tip {
  text-align: center;
  padding: 20rpx;
  font-size: 28rpx;
  color: #999;
}

.function-list {
  margin-top: 30rpx;
}

.function-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.arrow {
  width: 20rpx;
  height: 20rpx;
}

.nurse-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 100rpx;
  background-color: #F8F8F8;
  border-top: 1rpx solid #e5e5e5;
}

.tab-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.tab-icon {
  width: 48rpx;
  height: 48rpx;
}

.tab-text {
  font-size: 24rpx;
  color: #666;
}

.tab-item.active .tab-text {
  color: #018d71;
}
</style>
